from MLBase import MachineLearingBase 
import numpy
import SortMoudle
#这是一个 KNN 的机器学习代码例子
class KNNMachine(MachineLearingBase):
    def Training(self,trainingData):
        #print("KNN原型的学习很简单，其实仅仅是将训练集数据记录下来，只有再后续预测的时候才根据选定的预测方案计算\"距离\"")
        self.calcData = numpy.array(trainingData)
    def Predict(self,preData,k=20,ord = 2):
        #print("Predict")
        #print(self.calcData)
        #print(self.calcData[1][0])
        #print(dataTest - self.calcData[1][0])
        
        res = [];
        preDataNp = numpy.array(preData)
        i = 0;
        while(i<len(self.calcData)):
            preDatadis2CurPoint = numpy.linalg.norm(preDataNp-self.calcData[i][0],ord)
            #print(preDatadis2CurPoint,i)
            res.append([preDatadis2CurPoint,i,self.calcData[i][1]])
            i = i+1
        
        def CompFun(a,b):
            #print("Enter CompFun(a,b)1",a[0],b[0])
            if a[0]>b[0]:
                #print("return a")
                return a
            else:
                #print("return b")
                return b

        SortMoudle.SortUserDefFun(res,CompFun)
        #print
        i=0
        while(i<len(res)):
            i = i+1
        #pring

        classRes = [];#classRes中的元素是个二维数组 [x1,x2]x1中和calcData中的分类结果对应，x2是已经找到的该类的数目
        i = 0
        while(i<k):
            typeFind = False
            for j in classRes:
                if j[0]==res[i][2]:
                    typeFind = True
                    j[1] = j[1] + 1
                    break
            if typeFind == False:
                classRes.append([res[i][2],1])
            i = i+1

        def CompFun(a,b):
            if a[1]<b[1]:
                return a
            else:
                return b
        SortMoudle.SortUserDefFun(classRes,CompFun)

        #print
        i=0;
        while(i<len(classRes)):
            #print("classRes[{}]:Type:{},Num:{}".format(i,classRes[i][0],classRes[i][1]))
            i = i+1
        #
        return classRes[0][0]